<?php
class CommonModel extends Model {
       //替换操作
       function TemplateReplace($key,$value,$subject)
        {
          return   preg_replace("/\{".$key."\}/i",$value,$subject);
        } 
      //生成查询  
      function buildWhere($P)
        {
           $w="";
           $qtypes=preg_split("/,/",$P["qtype"]);
           $querys= preg_split("/,/",$P["query"]);
           for($i=0;$i<count($qtypes);$i++){
             $w.="{$qtypes[$i]} like '%{$querys[$i]}%' and "; 
           }
           if(substr($w,strlen($w)-4,4)=="and ")
           $w=substr($w,0,strlen($w)-4); 
           //print_r($w);
           return $w;
            
        }
              //生成json数据
    public function  json($action,$sql,$P,$primaryKey)
    {
        
        //以下为模板      
       $sql0=$sql." where {where} order by {order} limit {start},{end}";
       $sql1=$sql." where {where}";
        $page=$P['page'];
        $rp=$P['rp'];
        $sortname=$P['sortname'];
        $sortorder=$P['sortorder'];
        $qtype=$P['qtype'];
        $query=$P['query'];
        if(!$sortorder) $sortorder="asc";
        if(!$sortname) $sortname="id";  
        if(!$page) $page=1;   
        if(!$rp ) $rp =10;
        $where=$this->buildWhere($P);
        $order= $sortname." ".$sortorder;
        $start=($page-1)*$rp;
        $end=$rp;
        $sql0=$this->TemplateReplace("where",$where,$sql0);
        $sql0=$this->TemplateReplace("order",$order,$sql0);
        $sql0=$this->TemplateReplace("start",$start,$sql0);
        $sql0=$this->TemplateReplace("end",$end,$sql0);
        $data=array();
        $data[0]=$this->db->query($sql0);
        $data[1]=$page;
        $sql1=$this->TemplateReplace("where",$where,$sql1);
        $data[2]=count($this->db->query($sql1));
        if(method_exists($action,'buildJSON'))
        {
         header("Content-type:text/html;charset=utf-8");   //这句很重要,防止乱码   
         echo $action->buildJSON($data[0],$primaryKey,$data[1],$data[2]);
        }
        return $data;
    }
}
?>